from signInfo import Ui_Dialog
from PyQt5.QtWidgets import QDialog, QMessageBox, QTableWidgetItem, QFileDialog
from PyQt5.QtCore import QTimer
import requests
import sqlite3
import csv


class signWindow(Ui_Dialog, QDialog):
    def __init__(self, token, data_list, parent=None):
        super(signWindow, self).__init__(parent)
        self.setupUi(self)  # 创建界面内容
        self.data_list = data_list
        self.access_token = token
        self.db = sqlite3.connect("database.db")
        self.cursor = self.db.cursor()
        self.get_signed_data()
        self.get_no_signed_data()
        self.pushButton.clicked.connect(self.export_data)
        self.pushButton_2.clicked.connect(self.cancel)


    def get_signed_data(self):
        self.signed_list = []
        self.tableWidget.clear()
        select_sql = "SELECT * FROM SIGNIN"
        data = self.cursor.execute(select_sql)
        self.tableWidget.setHorizontalHeaderLabels(["学号", "班级", "姓名", "签到时间"])
        row = 0
        for x in data:
            self.tableWidget.insertRow(row)
            self.tableWidget.setItem(row, 0, QTableWidgetItem(x[0]))
            self.tableWidget.setItem(row, 1, QTableWidgetItem(x[1]))
            self.tableWidget.setItem(row, 2, QTableWidgetItem(x[2]))
            self.tableWidget.setItem(row, 3, QTableWidgetItem(x[3]))
            a = x[0] + '-' + x[1]
            self.signed_list.append(a)
            row += 1


    def get_no_signed_data(self):
        self.tableWidget_2.clear()
        self.tableWidget_2.setHorizontalHeaderLabels(["学号", "班级", "姓名"])
        row = 0
        for x in self.data_list:
            if x not in self.signed_list:
                user_id, group_id = x.split("-")
                self.tableWidget_2.insertRow(row)
                self.tableWidget_2.setItem(row, 0, QTableWidgetItem(user_id))
                self.tableWidget_2.setItem(row, 1, QTableWidgetItem(group_id))
                _, user_info = self.get_userInfo(user_id, group_id).split(": ")
                self.tableWidget_2.setItem(row, 2, QTableWidgetItem(user_info))
                row += 1


    def get_userInfo(self, user_id, group_id):
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/get"

        params = {
            "user_id": user_id,
            "group_id": group_id
        }
        access_token = self.access_token
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            message = response.json()
            if message['error_code'] == 0:
                return message['result']['user_list'][0]['user_info']
            else:
                return []


    def export_data(self):
        data = []
        if self.tabWidget.currentIndex() == 0:
            row = self.tableWidget.rowCount()
            if row == 0:
                QMessageBox.information(self, "information", "没有可导出的数据！")
                return
            data.append(["学号", "班级", "姓名", "签到时间"])
            for i in range(row):
                list = []
                list.append(self.tableWidget.item(i, 0).text())
                list.append(self.tableWidget.item(i, 1).text())
                list.append(self.tableWidget.item(i, 2).text())
                list.append(self.tableWidget.item(i, 3).text())
                data.append(list)
            filename, ret = QFileDialog.getSaveFileName(self, "导出已签数据", ".", "CSV(*.csv)")
        else:
            row = self.tableWidget_2.rowCount()
            if row == 0:
                QMessageBox.information(self, "information", "没有可导出的数据！")
                return
            data.append(["学号", "班级", "姓名"])
            for i in range(row):
                list = []
                list.append(self.tableWidget_2.item(i, 0).text())
                list.append(self.tableWidget_2.item(i, 1).text())
                list.append(self.tableWidget_2.item(i, 2).text())
                data.append(list)
            filename, ret = QFileDialog.getSaveFileName(self, "导出未签数据", ".", "CSV(*.csv)")

        # 数据写入
        with open(filename, 'w', encoding='utf-8', newline='') as file:
            writer = csv.writer(file, dialect='excel')
            for row in data:
                writer.writerow(row)


    def cancel(self):
        self.close()